﻿layui.use(['table', 'dropdown', 'layer', 'form'], function () {
    var table = layui.table;
    var dropdown = layui.dropdown;
    var layer = layui.layer;
    var form = layui.form;
    var laypage = layui.laypage;
    //钩子函数
    $(function () {
        RShow();
    });
    //显示方法
    window.RShow = function RShow() {
        //显示
        layui.use(function () {
            var table = layui.table;
            //查询条件
            var reservoirName = $("#ReservoirName").val();
            var reservoirNo = $("#ReservoirNo").val();
            // 创建渲染实例
            table.render({
                elem: '#reservoirTable',
                page: {
                    limit: 5,
                    limits: [5, 8, 10]
                },
                cols: [[
                    { type: 'checkbox', fixed: 'left' },
                    { field: 'reservoirName', width: 150, title: '库区名称' },
                    { field: 'reservoirNo', width: 180, title: '库区编号' },
                    { field: 'reservoirArea', width: 150, title: '面积' },
                    { field: 'warehouseName', width: 150, title: '所属仓库' },
                    { field: 'binLocationNum', width: 150, title: '库位数量' },
                    { field: 'reservoirRemark', width: 150, title: '备注' },
                    {
                        fixed: '', title: '操作', width: 180, templet: function (d) {
                            return '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="editData(' + d.reservoirId + ')">编辑</a>'
                                + '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick ="deleteData(' + d.reservoirId + ')">删除</a> '
                        }
                    }
                ]],
                // 初始时可以先不加载数据，等待 ajax 请求成功后再更新
                data: []
            });

            $.ajax({
                url: '/Warehouse/GetReservoirsShow',
                type: 'get',
                data: {
                    pageindex: 1,
                    pagesize: 100,
                    token: "",
                    ReservoirName: reservoirName,
                    ReservoirNo: reservoirNo,
                },
                success: function (data) {
                    data = JSON.parse(data);
                    console.log(data.data.list);
                    // 在 ajax 请求成功后，使用正确的表格 ID 进行 reload
                    table.reload('reservoirTable', {
                        page: {
                            limit: 5,
                            limits: [5, 8, 10]
                        },
                        data: data.data.list
                    });
                },
                error: function (res, msg) {
                    console.log(res, msg)
                }
            })

        });
    }

    //添加弹出层
    window.openEject = function openEject() {

        layer.open({
            type: 1, // page 层类型
            area: ['500px', '500px'],
            title: '仓库管理/ 库区管理 / 添加',
            shade: 0.4, // 遮罩透明度
            shadeClose: true, // 点击遮罩区域，关闭弹层
            maxmin: true, // 允许全屏最小化
            anim: 0, // 0-6 的动画形式，-1 不开启
            content: `
          <div style="margin: 16px;">
            <form class="layui-form layui-form-pane" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">库区名称:</label>
                    <div class="layui-input-block">
                        <input type="text" id="reservoirName1" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">库区编号:</label>
                    <div class="layui-input-block">
                        <input type="text" id="reservoirNo"  lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">面积:</label>
                    <div class="layui-input-block">
                        <input type="text" id="ReservoirArea" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">所属仓库:</label>
                    <div class="layui-input-block">
                        <select id="WarehouseId" lay-filter="cangku"></select>
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">备注:</label>
                     <div class="layui-input-block">  
                        <textarea id="ReservoirRemark" placeholder="请输入内容" class="layui-textarea"></textarea>
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button type="button" class="layui-btn layui-btn-primary" onclick="location.href='/Warehouse/ReservoirsShow'">取消</button>
                        <button type="button" class="layui-btn" lay-submit lay-filter="demo1" onclick="reservoirsAdd()" >添加</button>
                    </div>
                  </div>
            </form>
          </div>
        `,
        });
        select();
        aaa();
    }
    //加载下拉框仓库
    function select() {
        //加载仓库下拉框
        $.ajax({
            url: "/Warehouse/GetWarehouseList",
            type: "get",
            data: { token: localStorage.getItem("token") },
            //dataType: 'json', // 如果服务器返回的是 JSON 字符串，请移除这一行；如果返回的是 JSON 对象，请保留
            success: function (response) {
                // 如果服务器已经返回了 JSON 对象，则不需要再次解析
                var data = JSON.parse(response); // 请移除这一行，如果 response 已经是 JSON 对象
                //console.log(data.data);

                var options = '<option value="">请选择</option>'; // 添加默认选项
                $.each(data.data, function (index, item) {
                    // 使用正确的参数：index（索引）和 item（当前元素）
                    options += '<option value="' + item.warehouseId + '">' + item.warehouseName + '</option>';
                });

                $("#WarehouseId").html(options); // 设置下拉框的选项
                form.render(); // 重新渲染下拉框（确保 layui.form 已经被正确加载）
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("获取数据失败: " + textStatus, errorThrown);
                // 可以考虑显示一个错误消息给用户，例如使用 layui 的 layer 模块
                // layer.msg('获取仓库列表失败，请稍后再试'); // 确保 layer 已经被加载和初始化
            }
        });
    }
    //加载库区编号
    var obj = {
        ReservoirId: '',
        ReservoirName: '',
        ReservoirNo: '',
        ReservoirArea: '',
        WarehouseId: '',
        ReservoirRemark: '',
        BinLocationNum: '',
        CreatedBy: "",
        CreatedDate: "",
        UpdatedBy: "",
        UpdatedDate: "",
        DeletedBy: "",
        DeletedDate: "",
        IsDeleted: "",
    }
    //自动生成库区编号
    function aaa() {

        var n = new Date();
        var ss = "KQ" + n.getFullYear() + (n.getMonth() + 1).toString().padStart(2, '0') +
            n.getDate().toString().padStart(2, '0') +
            n.getHours().toString().padStart(2, '0') +
            n.getMinutes().toString().padStart(2, '0') +
            n.getSeconds().toString().padStart(2, '0');
        $("#reservoirNo").val(ss);
        obj.ReservoirNo = ss;
        console.log(obj.ReservoirNo);
    }
    //添加
    window.reservoirsAdd = function reservoirsAdd() {
        //debugger
        obj.ReservoirName = $("#reservoirName1").val()
        obj.ReservoirArea = $("#ReservoirArea").val()
        obj.WarehouseId = $("#WarehouseId").val()
        obj.ReservoirRemark = $("#ReservoirRemark").val()
        //obj.ReservoirNo = JSON.stringify(obj.ReservoirNo);
        console.log(obj);
        $.ajax({
            url: '/Warehouse/AddReservoirs',
            type: 'post',
            data: {
                ReservoirName: obj.ReservoirName,
                ReservoirNo: obj.ReservoirNo,
                ReservoirArea: obj.ReservoirArea,
                WarehouseId: obj.WarehouseId,
                ReservoirRemark: obj.ReservoirRemark,
                token: localStorage.getItem("token")
            },
            success: function (res) {
                //console.log(res)
                var res = JSON.parse(res)
                if (res.code == 0) {
                    alert("添加成功")
                    window.location.href = '/Warehouse/ReservoirsShow'
                }
                else {
                    alert("添加失败")
                }
            }
        })
    }

    //删除仓库
    window.deleteData = function (reservoirId) {
        layer.confirm("确认要删除吗?", function (index) {
            console.log(reservoirId);
            $.ajax({
                type: 'post',
                url: '/Warehouse/DelReservoirs',
                data: {
                    ReservoirId: reservoirId,
                    token: localStorage.getItem("token")
                },
                success: function (res) {
                    var obj = JSON.parse(res);
                    if (obj.code === 0) {
                        layer.msg("删除成功");
                        RShow();//重新加载显示
                    }
                    else {
                        layer.msg("删除失败");
                    }
                },
                error: function (err) {
                    layer.msg('删除失败，请稍后再试', {
                        time: 2000,
                        icon: 2
                    })
                }
            })
            layer.close(index);
        })
    }
    //编辑仓库
    window.editData = function editData(reservoirId) {
        layer.open({
            type: 1, // page 层类型
            area: ['500px', '500px'],
            title: '仓库管理/库区管理/编辑',
            shade: 0.4, // 遮罩透明度
            shadeClose: true, // 点击遮罩区域，关闭弹层
            maxmin: true, // 允许全屏最小化
            anim: 0, // 0-6 的动画形式，-1 不开启
            content: `
          <div style="margin: 16px;">
            <form class="layui-form layui-form-pane" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">库区名称:</label>
                    <div class="layui-input-block">
                        <input type="text" id="reservoirName1" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">库区编号:</label>
                    <div class="layui-input-block">
                        <input type="text" id="reservoirNo"  lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">面积:</label>
                    <div class="layui-input-block">
                        <input type="text" id="ReservoirArea" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">所属仓库:</label>
                    <div class="layui-input-block">
                        <select id="WarehouseId" lay-filter="cangku"></select>
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <label class="layui-form-label">备注:</label>
                     <div class="layui-input-block">  
                        <textarea id="ReservoirRemark" placeholder="请输入内容" class="layui-textarea"></textarea>
                    </div>
                  </div>
                  <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button type="button" class="layui-btn layui-btn-primary" onclick="location.href='/Warehouse/ReservoirsShow'">取消</button>
                        <button type="button" class="layui-btn" lay-submit lay-filter="demo1" onclick="reservoirsUpd()" >修改</button>
                    </div>
                  </div>
            </form>
          </div>
        `,
            success: function (layero, index, that) {
                //加载仓库下拉框
                $.ajax({
                    url: "/Warehouse/GetWarehouseList",
                    type: "get",
                    data: { token: localStorage.getItem("token") },
                    //dataType: 'json', // 如果服务器返回的是 JSON 字符串，请移除这一行；如果返回的是 JSON 对象，请保留
                    success: function (response) {
                        // 如果服务器已经返回了 JSON 对象，则不需要再次解析
                        var data = JSON.parse(response); // 请移除这一行，如果 response 已经是 JSON 对象
                        //console.log(data.data);

                        var options = '<option value="">请选择</option>'; // 添加默认选项
                        $.each(data.data, function (index, item) {
                            // 使用正确的参数：index（索引）和 item（当前元素）
                            options += '<option value="' + item.warehouseId + '">' + item.warehouseName + '</option>';
                        });

                        $("#WarehouseId").html(options); // 设置下拉框的选项
                        form.render(); // 重新渲染下拉框（确保 layui.form 已经被正确加载）

                        //返填
                        $.ajax({
                            url: '/Warehouse/ReservoirBackfill',
                            type: 'get',
                            data: {
                                ReservoirId: reservoirId,
                                token: '',
                            },
                            success: function (res) {
                                var res = JSON.parse(res);
                                console.log(res);
                                $.each(res, function () {
                                    $("#reservoirName1").val(this.reservoirName);
                                    $("#reservoirNo").val(this.reservoirNo);
                                    $("#ReservoirArea").val(this.reservoirArea);
                                    $("#WarehouseId").val(this.warehouseId);
                                    $("#ReservoirRemark").val(this.reservoirRemark);
                                    $("#createdBy").val(this.createdBy);
                                    localStorage["reservoirId"] = reservoirId;
                                    obj.ReservoirId = this.reservoirId,
                                        obj.ReservoirName = this.reservoirName,
                                        obj.ReservoirNo = this.reservoirNo,
                                        obj.ReservoirArea = this.reservoirArea,
                                        obj.WarehouseId = this.warehouseId,
                                        obj.ReservoirRemark = this.reservoirRemark,
                                        obj.CreatedBy = this.createdBy,
                                        obj.CreatedDate = this.CreatedDate
                                    form.render();
                                })
                            },
                        })
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.log("获取数据失败: " + textStatus, errorThrown);
                        // 可以考虑显示一个错误消息给用户，例如使用 layui 的 layer 模块
                        // layer.msg('获取仓库列表失败，请稍后再试'); // 确保 layer 已经被加载和初始化
                    }
                });
            }
        });
        
        //修改弹框
        

        window.reservoirsUpd = function reservoirsUpd() {
            var dto = {
                ReservoirId: '',
                ReservoirName: '',
                ReservoirNo: '',
                ReservoirArea: '',
                WarehouseId: '',
                ReservoirRemark: '',
                BinLocationNum: '',
                CreatedBy: "",
                CreatedDate: "",
                UpdatedBy: "",
                UpdatedDate: "",
                DeletedBy: "",
                DeletedDate: "",
                IsDeleted: "",
            }
            //debugger
            dto.CreatedBy = obj.CreatedBy
            dto.CreatedDate = obj.CreatedDate
            dto.ReservoirId = obj.ReservoirId
            dto.ReservoirName = $("#reservoirName1").val()
            dto.ReservoirArea = $("#ReservoirArea").val()
            dto.WarehouseId = $("#WarehouseId").val()
            dto.ReservoirRemark = $("#ReservoirRemark").val()
            dto.ReservoirNo = $("#reservoirNo").val()
            $.ajax({
                url: '/Warehouse/UpdReservoir',
                type: 'post',
                data: {
                    dto:dto,
                    token: localStorage.getItem("token")
                },
                success: function (res) {
                    //console.log(res)
                    var res = JSON.parse(res)
                    if (res.code == 0) {
                        alert("修改成功")
                        window.location.href = '/Warehouse/ReservoirsShow'
                    }
                    else {
                        alert("修改失败")
                    }
                }
            })
        }
    }
})
